package com._520it._02_one2many.test;

import com._520it._02_one2many.domain.Department;
import com._520it._02_one2many.domain.Employee;
import com._520it._02_one2many.mapper.DepartmentMapper;
import com._520it._02_one2many.mapper.EmployeeMapper;
import com._520it.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;


public class App {
    @Test
    public void testSave() throws Exception {

        //mapper接口代理对象实现了接口中的方法, 因此才会有mapper接口对象调用empmapper.save(employee1);
        SqlSession session = MybatisUtil.getSession();
        EmployeeMapper empmapper = session.getMapper(EmployeeMapper.class);
        DepartmentMapper depmapper = session.getMapper(DepartmentMapper.class);
        //===========================================================================

        //创建一个部门
        Department department = new Department();
        department.setName("开发部");

        //创建多个对象,设置属性
        Employee employee1 = new Employee();
        employee1.setName("王丹");
        Employee employee2 = new Employee();
        employee2.setName("李菲菲");

        //根据类的结构关系,维护对象间的关系, 将many方设置为one方的属性
        List<Employee> empls = department.getEmployeelist();
        empls.add(employee1);
        empls.add(employee2);

        //保存
        depmapper.save(department);
        empmapper.save(employee1);
        empmapper.save(employee2);

        //更新关系-----部门要更新与每个员工的关系
        for (Employee empl : empls) {
            depmapper.updateRelation(department.getId(), empl.getId());
        }
        //===========================================================================
        session.commit();
        session.close();
    }


    //通过部门的id, 发送额外SQL查询得到多个员工
    @Test
    public void testGet() throws Exception {
        SqlSession session = MybatisUtil.getSession();
        DepartmentMapper depmapper = session.getMapper(DepartmentMapper.class);
        //===========================================================================

        //部门对象, 封装了员工集合属性
        Department department = depmapper.get(5L);
        for (Employee employee : department.getEmployeelist()) {
         System.out.println(employee);
        }
        session.close();
    }

    //显示内连接的方式查询
    @Test
    public void testList() throws Exception {
        SqlSession session = MybatisUtil.getSession();
        DepartmentMapper depmapper = session.getMapper(DepartmentMapper.class);
        //===========================================================================

        //部门对象, 封装了员工集合属性
        List<Department> list = depmapper.list();
        for (Department depart : list) {
            System.out.println(depart.getEmployeelist());
        }
        session.close();

    }


}
